const requests = require("../../../utils/request")

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    addressData:[]
  },
  async onchangeDefault(e)
  {
    console.log(e.currentTarget)
    const defualtAddressId = e.currentTarget.id
    let addressData = this.data.addressData
    for(let i in addressData)
    {
      let item = addressData[i]
      if(item.addressId==defualtAddressId)
      {
        item.isdefault=true
        let tmp = addressData[0]
        addressData[0]=item
        addressData[i]=tmp
        //修改内存
        wx.setStorage({
          key:"address",
          data:item
        })
        //修改数据库
        let res1= await requests.addressInterface(null,defualtAddressId,null,null,app.globalData.openid,1,'saveOrUpdate')
        let res2= await requests.addressInterface(null,this.data.addressData[0].addressId,null,null,app.globalData.openid,0,'saveOrUpdate')

      }
      else{
        item.isdefault=false
      } 
  }
    this.setData({
      addressData
    })
  },
  editAddress(e)
  {
    wx.navigateTo({
      url: './editAddress/index?address='+ JSON.stringify(e.currentTarget.dataset.address),
    })
  },
  chooseAdress(e)
  {
    const addressChosed=e.currentTarget.dataset.addresschoosed
    // console.log(addressChosed)
    wx.setStorage({
      key:"address",
      data:addressChosed
    })
    wx.navigateBack({
      delta: 0,
    })

  },
  addAddress(){
    var defaultId
    if(this.data.addressData.length>0)
    {
     defaultId = this.data.addressData[0].addressId
    }
    else
    {
      defaultId = null
    }
    wx.navigateTo({
      url: `./addAddress/index?defaultId=${defaultId}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow:async function () {
    var that = this
    let res= await requests.getAddressByOrder(app.globalData.openid)
    // console.log('address',res.data.data.value)
    let addressList = res.data.data.value
    
    that.setData({
      addressData:addressList
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})